package cn.tedu.charging.account.service.impl;

import cn.tedu.charging.account.dao.persist.repository.IChargingDeviceRepository;
import cn.tedu.charging.account.dao.persist.repository.IChargingStationRepository;
import cn.tedu.charging.account.dao.persist.repository.IOrderRepository;
import cn.tedu.charging.account.pojo.entity.ChargingDevice;
import cn.tedu.charging.account.pojo.entity.ChargingStation;
import cn.tedu.charging.account.pojo.vo.ChargingStationStandardVO;
import cn.tedu.charging.account.pojo.vo.OrderStandardVO;
import cn.tedu.charging.account.service.IChargingStationService;
import cn.tedu.charging.account.service.geo.IRedisGeoCache;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.*;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * 处理充电站数据的业务实现类
 *
 * @author wyy
 * @version 1.0
 */
@Service
@Slf4j
public class ChargingStationServiceImpl implements IChargingStationService {

    @Autowired
    private IChargingStationRepository repository;

    @Autowired
    private IOrderRepository orderRepository;

    @Autowired
    private IRedisGeoCache redisGeoCache;

    @Override
    public void addNew(ChargingStation chargingStation) {
        int insert = repository.insert(chargingStation);
        log.debug("插入{}条数据", insert);
    }

    @Override
    public void delete(Long id) {
        int delete = repository.deleteById(id);
        log.debug("删除{}条数据", delete);
    }

    @Override
    public void update(ChargingStation chargingStation) {
        int update = repository.updateById(chargingStation);
        log.debug("修改了{}条数据", update);

    }

    @Override
    public Long countListByStationId(String bean) {
        List<ChargingStation> chargingStations = repository.selectAll();
        Long rows = redisGeoCache.saveChargingStationToRedis(chargingStations);
        return rows;
    }

    @Override
    public List<ChargingStationStandardVO> findByLocationWithin(double latitude, double longitude, double radius, String name) {
        log.debug("参数：{}， {}，{}", latitude, longitude, radius);
        Point center = new Point(longitude, latitude);
        Distance distance = new Distance(radius, Metrics.KILOMETERS);
        Circle circle = new Circle(center, distance);
        RedisGeoCommands.GeoRadiusCommandArgs args =
                RedisGeoCommands.GeoRadiusCommandArgs.newGeoRadiusArgs().includeDistance().limit(50).sortAscending();
        GeoResults<RedisGeoCommands.GeoLocation<Long>> pointRadius = redisGeoCache.getPointRadius(circle, args);
        List<GeoResult<RedisGeoCommands.GeoLocation<Long>>> content = pointRadius.getContent();
        ArrayList<Long> ids = new ArrayList<>();
        for (GeoResult<RedisGeoCommands.GeoLocation<Long>> geoLocationGeoResult : content) {
            RedisGeoCommands.GeoLocation<Long> content1 = geoLocationGeoResult.getContent();
            Long idName = content1.getName();
            log.debug("name = {}", name );
            ids.add(idName);
        }

        List<ChargingStationStandardVO> chargingStationStandardVOS = new ArrayList<>();
        if (ids.size() < 1) {
            return chargingStationStandardVOS;
        }

        List<ChargingStationStandardVO> stationStandardVOS = repository.selectAllChargingDevice(ids, name);
        for (ChargingStationStandardVO stationStandardVO : stationStandardVOS) {
            for (GeoResult<RedisGeoCommands.GeoLocation<Long>> geoLocationGeoResult : content) {
                RedisGeoCommands.GeoLocation<Long> content1 = geoLocationGeoResult.getContent();
                Long idName = content1.getName();
                if (stationStandardVO.getId() == idName) {
                    double value = geoLocationGeoResult.getDistance().getValue();
                    if (value > 1) {
                        String value1 = value + "km";
                        stationStandardVO.setDistance(value1);
                    } else {
                        BigDecimal km = new BigDecimal(value + "");
                        BigDecimal m = km.multiply(new BigDecimal("1000"));
                        String result = m + "m";
                        stationStandardVO.setDistance(result);
                    }
                }
            }
        }
        return stationStandardVOS;
    }

    @Override
    public OrderStandardVO selectByStationDeviceId(Long id, Integer userId) {
        // 参数  充电枪id、用户id
        // 0：通过设备id获取充电枪数据
        // 1：判断充电枪是否损坏 如果损坏，直接返回
        // 2：否则，判断充电枪是否正在空闲中，如果空闲中，直接返回相关数据（单价）
        // 3：如果在使用中，通过userID和设备id查询正在进行中的订单数据，
        // 如果订单数据不为空，说明为当前用户使用中
        // 否则说明为其他用户使用中
        log.debug("开始根据充电站id{}查询是否被使用", id);
        OrderStandardVO orderStandardVO = orderRepository.selectByDeviceId(id, userId);
        if (orderStandardVO == null) {
            // 当前设备id+userID查询不到数据，说明当前设备不是被当前用户使用
            OrderStandardVO orderStandardVO1 = new OrderStandardVO();
            orderStandardVO1.setStatus(2);
            return orderStandardVO1;
        }
        Integer status = orderStandardVO.getStatus();
        if (status == 0) {
            orderStandardVO.setStatus(3);
            return orderStandardVO;
        }
        return null;
    }
}
